﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using Foothill.Bus;
using Foothill.Bus.Result;
using Foothill.Bus.Node;
using Foothill.Persistent.Command;
using Foothill.Core.FieldMapping;
using GGFW.Entity.DocumentsManage;
using GGFW.DataAccess.Constants;

namespace GGFW.DataAccess.DocumentsManage
{
    public class OrdersDao : BaseDao
    {
        #region 分页查询订单信息(v_orders)
        /// <summary>
        /// 分页查询订单信息(v_orders)
        /// </summary>
        /// <param name="PageSize"></param>
        /// <param name="PageIndex"></param>
        /// <param name="v_ordersEntity"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        public List<v_orders> QueryByPageViewOrders(int PageSize, int PageIndex, v_orders v_ordersEntity, out int totalCount)
        {
            string querySql = this.getQuerySqlerOrder(v_ordersEntity);

            //结果总数
            totalCount = this.GetQueryCount(querySql);
            querySql += this.getOrderSql(v_ordersEntity);
            //设置查询企业基本信息总线
            NativeSqlBus queryBus = new NativeSqlBus("v_orders", querySql);

            //执行查询业务代码命令
            QueryNativeSqlCommand queryCommand = new QueryNativeSqlCommand(queryBus);
            ResultQueryNativeSql result = queryCommand.executePage(PageIndex, PageSize) as ResultQueryNativeSql;


            //执行结果为空
            if (result == null)
            {
                throw new Exception(GGFW.DataAccess.Constants.Common.UNKNOW_DB_ERROR);
            }

            //执行命令不成功
            if (!result.isSuccess())
            {
                throw new Exception(result.getMessage());
            }

            //是否存在记录
            if (result.Records != null && result.Records.Count > 0)
            {
                List<v_orders> dataList = new List<v_orders>();
                AbstractResultBus.CopyProperties<v_orders>(dataList, result.Records, null);
                MappingFieldEvaluator.ProcessList<v_orders>(dataList);

                return dataList;
            }
            return null;
        }

        /// <summary>
        /// 获得排序语句
        /// </summary>
        /// <param name="v_ordersEntity">查询条件</param>
        /// <returns>排序语句</returns>
        private string getOrderSql(v_orders v_ordersEntity)
        {
            string OrderField = "";
            if (!string.IsNullOrEmpty(v_ordersEntity.OrderField))
            {
                OrderField = v_ordersEntity.OrderField;
            }
            return SqlUtil.GetOrderSql(OrderField, v_ordersEntity.OrderDirection, "order_id", "desc");
        }

        /// <summary>
        /// 获取订单列表
        /// </summary>
        /// <param name="v_ordersEntity"></param>
        /// <returns></returns>
        private string getQuerySqlerOrder(v_orders v_ordersEntity)
        {
            StringBuilder sqlText = new StringBuilder();
            sqlText.Append("select distinct * from v_orders where isdeleted =0");
            //是否查询订单编号
            if (v_ordersEntity.order_id != 0)
            {
                sqlText.Append(string.Format(" and order_id = '{0}' ", v_ordersEntity.order_id));
            }
            if (!string.IsNullOrEmpty(v_ordersEntity.order_po))
                sqlText.Append(string.Format(" and order_po like '%{0}%' ", v_ordersEntity.order_po));
            if (!string.IsNullOrEmpty(v_ordersEntity.client_name))
                sqlText.Append(string.Format(" and client_name like '%{0}%' ", v_ordersEntity.client_name));
            return sqlText.ToString();
        }
        #endregion

        #region 保存订单主表信息
        /// <summary>
        /// 保存订单主表信息
        /// </summary>
        /// <param name="productFileds"></param>
        /// <returns></returns>
        public int SaveOrder(string orderFileds)
        {
            int pro_id = 0;
            string sql = "Insert into Orders({0}) values({1});select @@IDENTITY";
            string[] filed_NameValue = orderFileds.Split('ξ');
            string filed_Name = filed_NameValue[0];
            string filed_Value = filed_NameValue[1];
            sql = string.Format(sql, filed_Name, filed_Value);
            //设置查询企业基本信息总线
            NativeSqlBus queryBus = new NativeSqlBus("Orders", sql);

            //执行查询业务代码命令
            QueryNativeSqlCommand queryCommand = new QueryNativeSqlCommand(queryBus);
            ResultQueryNativeSql result = queryCommand.execute() as ResultQueryNativeSql;

            //执行结果为空
            if (result == null)
            {
                throw new Exception(Common.UNKNOW_DB_ERROR);
            }

            //执行命令不成功
            if (!result.isSuccess())
            {
                throw new Exception(result.getMessage());
            }

            //是否存在记录
            if (result.Records != null && result.Records.Count > 0)
            {
                pro_id = Convert.ToInt32(result.Records[0].Fields[0].FieldValue);
            }

            return pro_id;
        }
        #endregion

        #region 保存订单Grid表信息
        /// <summary>
        /// 保存订单Grid表信息
        /// </summary>
        /// <param name="ordergridFileds"></param>
        /// <param name="order_id"></param>
        public void SaveOrderGrid(string ordergridFileds, int order_id)
        {
            StringBuilder sb = new StringBuilder();
            string[] filed_NameValue = null;
            string filed_Name = null;
            string filed_Value = null;
            string sql = "Insert into ordersgrid({0}) values({1})";
            string[] arr_fileds = ordergridFileds.Split('₃');
            for (int i = 0; i < arr_fileds.Length; i++)
            {
                filed_NameValue = arr_fileds[i].Split('ξ');
                filed_Name = filed_NameValue[0];
                filed_Value = filed_NameValue[1].Replace("∮order_id∮", order_id.ToString());
                sb.Append(string.Format(sql, filed_Name, filed_Value));
                if (i < arr_fileds.Length - 1)
                    sb.Append(";");
            }

            //设置查询企业基本信息总线
            NativeSqlBus queryBus = new NativeSqlBus("ordersgrid", sb.ToString());

            //执行查询业务代码命令
            QueryNativeSqlCommand queryCommand = new QueryNativeSqlCommand(queryBus);
            ResultQueryNativeSql result = queryCommand.execute() as ResultQueryNativeSql;

            //执行结果为空
            if (result == null)
            {
                throw new Exception(Common.UNKNOW_DB_ERROR);
            }

            //执行命令不成功
            if (!result.isSuccess())
            {
                throw new Exception(result.getMessage());
            }
        }
        #endregion

        #region 分页查询订单信息(v_ordersinfo)
        /// <summary>
        /// 获取View_Orders
        /// </summary>
        /// <param name="PageSize"></param>
        /// <param name="PageIndex"></param>
        /// <param name="view_ordersEntity"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        public List<v_ordersinfo> QueryByPageViewOrdersInfo(int PageSize, int PageIndex, v_ordersinfo v_ordersinfoEntity, out int totalCount)
        {
            string querySql = this.getQuerySqlerViewOrders(v_ordersinfoEntity);

            //结果总数
            totalCount = this.GetQueryCount(querySql);
            querySql += this.getOrderSql(v_ordersinfoEntity);
            //设置查询企业基本信息总线
            NativeSqlBus queryBus = new NativeSqlBus("v_ordersinfo", querySql);

            //执行查询业务代码命令
            QueryNativeSqlCommand queryCommand = new QueryNativeSqlCommand(queryBus);
            ResultQueryNativeSql result = queryCommand.executePage(PageIndex, PageSize) as ResultQueryNativeSql;


            //执行结果为空
            if (result == null)
            {
                throw new Exception(GGFW.DataAccess.Constants.Common.UNKNOW_DB_ERROR);
            }

            //执行命令不成功
            if (!result.isSuccess())
            {
                throw new Exception(result.getMessage());
            }

            //是否存在记录
            if (result.Records != null && result.Records.Count > 0)
            {
                List<v_ordersinfo> dataList = new List<v_ordersinfo>();
                AbstractResultBus.CopyProperties<v_ordersinfo>(dataList, result.Records, null);
                MappingFieldEvaluator.ProcessList<v_ordersinfo>(dataList);

                return dataList;
            }
            return null;
        }


        /// <summary>
        /// 获取v_ordersinfo
        /// </summary>
        /// <param name="v_ordersinfoEntity"></param>
        /// <returns></returns>
        private string getQuerySqlerViewOrders(v_ordersinfo v_ordersinfoEntity)
        {
            StringBuilder sqlText = new StringBuilder();
            sqlText.Append("select distinct * from v_ordersinfo where 1=1");
            //是否查询订单编号
            if (v_ordersinfoEntity.order_id != 0)
            {
                sqlText.Append(string.Format(" and order_id = {0} ", v_ordersinfoEntity.order_id));
            }
            if (!string.IsNullOrEmpty(v_ordersinfoEntity.order_po))
                sqlText.Append(string.Format(" and order_po like '%{0}%' ", v_ordersinfoEntity.order_po));
            return sqlText.ToString();
        }

        /// <summary>
        /// 获得排序语句
        /// </summary>
        /// <param name="v_ordersinfoEntity"></param>
        /// <returns></returns>
        private string getOrderSql(v_ordersinfo v_ordersinfoEntity)
        {
            string OrderField = "";
            if (!string.IsNullOrEmpty(v_ordersinfoEntity.OrderField))
            {
                OrderField = v_ordersinfoEntity.OrderField;
            }
            return SqlUtil.GetOrderSql(OrderField, v_ordersinfoEntity.OrderDirection, "order_id", "asc");
        }
        #endregion

        #region 分页查询订单信息(v_mo)
        /// <summary>
        /// 分页查询订单信息(v_mo)
        /// </summary>
        /// <param name="PageSize"></param>
        /// <param name="PageIndex"></param>
        /// <param name="view_moEntity"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        public List<v_mo> QueryByPageViewMO(int PageSize, int PageIndex, v_mo v_moEntity, out int totalCount)
        {
            string querySql = this.getQuerySqlerViewMO(v_moEntity);

            //结果总数
            totalCount = this.GetQueryCount(querySql);
            querySql += this.getOrderSql(v_moEntity);
            //设置查询企业基本信息总线
            NativeSqlBus queryBus = new NativeSqlBus("v_mo", querySql);

            //执行查询业务代码命令
            QueryNativeSqlCommand queryCommand = new QueryNativeSqlCommand(queryBus);
            ResultQueryNativeSql result = queryCommand.executePage(PageIndex, PageSize) as ResultQueryNativeSql;


            //执行结果为空
            if (result == null)
            {
                throw new Exception(GGFW.DataAccess.Constants.Common.UNKNOW_DB_ERROR);
            }

            //执行命令不成功
            if (!result.isSuccess())
            {
                throw new Exception(result.getMessage());
            }

            //是否存在记录
            if (result.Records != null && result.Records.Count > 0)
            {
                List<v_mo> dataList = new List<v_mo>();
                AbstractResultBus.CopyProperties<v_mo>(dataList, result.Records, null);
                MappingFieldEvaluator.ProcessList<v_mo>(dataList);

                return dataList;
            }
            return null;
        }

        /// <summary>
        /// 获取v_mo
        /// </summary>
        /// <param name="v_moEntity"></param>
        /// <returns></returns>
        private string getQuerySqlerViewMO(v_mo v_moEntity)
        {
            StringBuilder sqlText = new StringBuilder();
            sqlText.Append("select distinct * from v_mo where 1=1");
            //是否查询订单编号
            if (v_moEntity.order_id != 0)
            {
                sqlText.Append(string.Format(" and order_id = {0} ", v_moEntity.order_id));
            }
            return sqlText.ToString();
        }

        /// <summary>
        /// 获得排序语句
        /// </summary>
        /// <param name="v_moEntity">查询条件</param>
        /// <returns>排序语句</returns>
        private string getOrderSql(v_mo v_moEntity)
        {
            string OrderField = "";
            if (!string.IsNullOrEmpty(v_moEntity.OrderField))
            {
                OrderField = v_moEntity.OrderField;
            }
            return SqlUtil.GetOrderSql(OrderField, v_moEntity.OrderDirection, "order_id", "asc");
        }
        #endregion

        #region 更新订单表(orders)信息
        /// <summary>
        /// 更新订单表(orders)信息
        /// </summary>
        /// <param name="OrderID"></param>
        /// <param name="TabName"></param>
        /// <param name="FiledName"></param>
        /// <param name="FiledValue"></param>
        /// <returns></returns>
        public bool UpdateOrdersInfo(string OrderID, string TabName, string FiledName, string FiledValue)
        {
            string sql = null;

            if (FindProductInfo(OrderID, TabName) == true)
                sql = string.Format("update {0} set {1}='{2}' where order_id={3}", TabName, FiledName, FiledValue, OrderID);
            else
                sql = string.Format("insert into {0} (order_id, {1}) values({2}, '{3}')", TabName, FiledName, OrderID, FiledValue);

            //设置查询企业基本信息总线
            NativeSqlBus queryBus = new NativeSqlBus(TabName, sql);


            //执行查询业务代码命令
            QueryNativeSqlCommand queryCommand = new QueryNativeSqlCommand(queryBus);
            ResultQueryNativeSql result = queryCommand.execute() as ResultQueryNativeSql;

            //执行结果为空
            if (result == null)
            {
                throw new Exception(Common.UNKNOW_DB_ERROR);
            }

            //执行命令不成功
            if (!result.isSuccess())
            {
                throw new Exception(result.getMessage());
            }

            return true;
        }

        /// <summary>
        /// 查询订单信息
        /// </summary>
        /// <param name="ProID"></param>
        /// <param name="TabName"></param>
        /// <returns></returns>
        public bool FindProductInfo(string OrderID, string TabName)
        {
            string sql = null;

            sql = string.Format("select * from {0} where order_id={1}", TabName, OrderID);

            //设置查询企业基本信息总线
            NativeSqlBus queryBus = new NativeSqlBus(TabName, sql);


            //执行查询业务代码命令
            QueryNativeSqlCommand queryCommand = new QueryNativeSqlCommand(queryBus);
            ResultQueryNativeSql result = queryCommand.execute() as ResultQueryNativeSql;

            //执行结果为空
            if (result == null)
            {
                throw new Exception(Common.UNKNOW_DB_ERROR);
            }

            //执行命令不成功
            if (!result.isSuccess())
            {
                throw new Exception(result.getMessage());
            }
            //是否存在记录
            if (result.Records != null && result.Records.Count > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        #endregion

        #region 更新订单表(ordersgrid)信息
        /// <summary>
        /// 更新订单表(ordersgrid)信息
        /// </summary>
        /// <param name="OgID"></param>
        /// <param name="OrderID"></param>
        /// <param name="FieldName"></param>
        /// <param name="FieldValue"></param>
        /// <returns></returns>
        public ordersgrid UpdateOrdersGridfield(string OgID, string OrderID, string FieldName, string FieldValue)
        {
            string sql = null;
            if (int.Parse(OgID) > 0)
            {
                sql = string.Format("update ordersgrid set {0}='{1}' where id='{2}'", FieldName, FieldValue, OgID);
            }
            else
            {
                sql = string.Format("insert into ordersgrid (order_id, {0}) values({1}, {2}); select @@IDENTITY", FieldName, OrderID, FieldValue);
            }

            //设置查询企业基本信息总线
            NativeSqlBus queryBus = new NativeSqlBus("ordersgrid", sql);


            //执行查询业务代码命令
            QueryNativeSqlCommand queryCommand = new QueryNativeSqlCommand(queryBus);
            ResultQueryNativeSql result = queryCommand.execute() as ResultQueryNativeSql;

            //执行结果为空
            if (result == null)
            {
                throw new Exception(Common.UNKNOW_DB_ERROR);
            }

            //执行命令不成功
            if (!result.isSuccess())
            {
                throw new Exception(result.getMessage());
            }
            //是否存在记录
            if (result.Records != null && result.Records.Count > 0)
            {
                ordersgrid og = new ordersgrid();
                og.id = Convert.ToInt32(result.Records[0].Fields[0].FieldValue);
                return og;
            }
            return null;
        }
        #endregion

        #region 删除订单
        /// <summary>
        /// 删除订单
        /// 并不真正删除，只是将isdeleted置为1
        /// </summary>
        /// <param name="order_id"></param>
        public void DelOrdersByID(int order_id)
        {
            string sql = string.Format("update orders set isdeleted=1 where order_id='{0}'", order_id);
            //设置查询企业基本信息总线
            NativeSqlBus queryBus = new NativeSqlBus("orders", sql);


            //执行查询业务代码命令
            QueryNativeSqlCommand queryCommand = new QueryNativeSqlCommand(queryBus);
            ResultQueryNativeSql result = queryCommand.execute() as ResultQueryNativeSql;

            //执行结果为空
            if (result == null)
            {
                throw new Exception(GGFW.DataAccess.Constants.Common.UNKNOW_DB_ERROR);
            }
            //执行命令不成功
            if (!result.isSuccess())
            {
                throw new Exception(result.getMessage());
            }
        }
        #endregion
    }
}
